<!--
 Copyright (C) 2016-2023 Jones Magloire @Joxit

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
-->
<copy-to-clipboard>
  <div class="copy-to-clipboard">
    <input style="display: none; width: 1px; height: 1px" value="{ getDockerCmd(props) }" />
    <material-button
      text-color="var(--neutral-text)"
      color="inherit"
      waves-color="var(--hover-background)"
      waves-center="true"
      onClick="{ copy }"
      title="Copy pull command."
      icon
    >
      <i class="material-icons">content_copy</i>
    </material-button>
  </div>
  <script>
    import { ERROR_CAN_NOT_READ_CONTENT_DIGEST } from '../../scripts/utils';
    export default {
      onMounted(props, state) {
        this.load(props, state);
      },
      onUpdated(props, state) {
        this.load(props, state);
      },
      getDockerCmd(props) {
        if (props.target === 'tag') {
          return `docker pull ${props.pullUrl}/${props.image.name}:${props.image.tag}`;
        } else {
          return `docker pull ${props.pullUrl}/${props.image.name}@${props.image.contentDigest}`;
        }
      },
      load(props, state) {
        if (props.target !== 'tag' && !props.image.contentDigest) {
          props.image.one('content-digest', (contentDigest) => {
            this.update();
          });
          props.image.trigger('get-content-digest');
        }
      },
      copy() {
        const copyText = this.$('input');
        if (!copyText.value) {
          this.props.onNotify(ERROR_CAN_NOT_READ_CONTENT_DIGEST);
          return;
        }

        copyText.style.display = 'block';
        copyText.select();
        document.execCommand('copy');
        copyText.style.display = 'none';

        this.props.onNotify('`' + copyText.value + '` has been copied to clipboard.');
      },
    };
  </script>
</copy-to-clipboard>
